import { createFileRoute } from '@tanstack/react-router'
import { useEffect, useRef } from 'react'
import { useAuth } from '@/contexts/AuthContext'
import { useNavigate } from '@tanstack/react-router'
import { LoginForm } from '@/components/LoginForm'

export const Route = createFileRoute('/login')({
  component: Login,
})

function Login() {
  const { isAuthenticated, isLoading } = useAuth()
  const navigate = useNavigate()
  const hasRedirected = useRef(false)

  useEffect(() => {
    // 如果用户已经登录且还没有重定向过，重定向到看板页面
    if (!isLoading && isAuthenticated && !hasRedirected.current) {
      hasRedirected.current = true
      // 使用setTimeout避免在渲染过程中导航
      setTimeout(() => {
        navigate({ to: '/dashboard', replace: true })
      }, 0)
    }
    
    // 如果用户未登录，重置重定向标志
    if (!isAuthenticated) {
      hasRedirected.current = false
    }
  }, [isAuthenticated, isLoading, navigate])

  // 如果正在加载或用户已登录，显示加载状态
  if (isLoading || isAuthenticated) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600 dark:text-gray-400">
            {isLoading ? '正在验证用户身份...' : '正在跳转到看板...'}
          </p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 dark:from-gray-900 dark:via-gray-800 dark:to-gray-700 py-12 px-4 sm:px-6 lg:px-8 relative overflow-hidden">
      {/* 装饰性背景元素 */}
      <div className="absolute inset-0 overflow-hidden">
        <div className="absolute -top-1/2 -left-1/2 w-full h-full bg-gradient-to-br from-blue-400/20 to-transparent rounded-full transform rotate-45"></div>
        <div className="absolute -bottom-1/2 -right-1/2 w-full h-full bg-gradient-to-tl from-indigo-400/20 to-transparent rounded-full transform -rotate-45"></div>
      </div>
      
      <div className="max-w-md w-full relative z-10">
        <div className="text-center mb-10">
          <div className="mb-8">
            <img 
              src="/images/huibanhao.png" 
              alt="惠办好" 
              className="h-20 w-auto mx-auto drop-shadow-lg"
            />
          </div>
          <h2 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            欢迎回来
          </h2>
          <p className="text-gray-600 dark:text-gray-300">
            登录您的账户以继续使用
          </p>
        </div>
        <LoginForm />
      </div>
    </div>
  )
}
